from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .models import Menu, Order
from .models import UserProfile
from .models import Restaurant
import time
import json


# Create your views here.
def index(request):
    return render(request, 'index.html')


def menu_add(request):
    if request.method == "GET":
        restaurants = Restaurant.objects.all()
        return render(request, 'menu_add.html', {"restaurants": restaurants})
    if request.method == "POST":
        name = request.POST.get("name", "")
        price = request.POST.get("price", "0")
        restaurant = request.POST.get("restaurant", "0")
        try:
            price = float(price)
        except:
            print('菜品价格输入格式不对')
            return HttpResponse("菜品价格输入格式不对")
        Menu.objects.create(name=name, price=price, restaurant_id=restaurant)
        return redirect('eatwell:index')


def menus(request):
    rid = request.GET.get('rid')  # 根据rid 判断是哪个餐馆

    menus = Menu.objects.filter(restaurant_id=rid).all()
    id = request.GET.get('id', '')  # 如果id,说明我在点餐
    # 查询订单数据库

    try:
        order = Order.objects.get(status='1')  # 获取状态
        print('继续点餐')
        # 获取到 goods
        goods = order.goods
        goods = json.loads(goods)
        if id:
            if id in goods:  # 曾经点过这种菜品
                goods[id] += 1
            else:
                goods[id] = 1
            # 将本次的改变也写入到数据库
            order.goods = json.dumps(goods)
            order.save()
    except:
        print('-----------异常了----------------')
        if id:
            orderid = str(int(time.time()))
            order = Order.objects.create(orderid=orderid, goods=json.dumps({id: 1}))

            print(order.goods)  # {'2': 1}
            print(type(order.goods))
            goods = json.loads(order.goods)
            print(goods)
        else:
            goods = {}
    res = Menu.objects.all()
    ids = []
    names = []
    for m in res.values('id'):
        ids.append(m.get('id'))
    for n in res.values('name'):
        names.append(n.get('name'))

    print(ids)
    print(names)
    kv = {str(x): y for x, y in zip(ids, names)}
    print(kv)

    # res 是个三元组  (菜品名称,菜品id,菜品数量)
    res = []
    total = 0  # 总付款数
    # 遍历订单中所有 菜品
    # 每个菜品* 数量  加在一起
    # todo
    for cai_id, cai_count in goods.items():  #
        res.append((kv.get(cai_id), cai_id, cai_count))
        total += Menu.objects.get(id=cai_id).price * cai_count

    return render(request, 'menus.html', {"menus": menus, "goods": res, "total": total})


def pay(request):
    order = Order.objects.get(status='1')
    order.status = '2'
    order.save()
    return HttpResponse('下单完成!')


def register(request):
    if request.method == "GET":
        return render(request, 'register.html')

    if request.method == "POST":
        username = request.POST.get("username")
        home_address = request.POST.get("home_address")
        phone = request.POST.get("phone")
        password = request.POST.get("password")
        jobs = request.POST.get("jobs")

        # 创建用户
        user = User.objects.create_user(username=username, password=password)
        print(type(user.id))
        print(type(user.username))
        userprofile = UserProfile(home_address=home_address, phone=phone, job=jobs, user_id=user.id)
        userprofile.save()

        return HttpResponse("注册成功")


def showuser(request):
    userid = request.GET.get('id', '')
    if not userid:
        return HttpResponse("没有id参数")

    user = User.objects.get(id=int(userid))
    print(user.username)
    # print(type(user.userprofile_set.all()))
    # phone =user.userprofile_set.all().first().phone
    phone = user.userprofile.phone
    print(phone, 'home')
    # todo 展示用户信息,更改用户信息界面  job字段不可以更改
    # return render(request,'showuser.html',{"user":user})
    return HttpResponse('展示用户信息')


def loginx(request):
    if request.method == "GET":
        return render(request, 'loginx.html')
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        print(username, password, '------->')

        user = authenticate(username=username, password=password)
        if user.username:  # 判断一下有这个用户
            login(request=request, user=user)
            job = user.userprofile.job  # 用户身份
            # 不同身份跳转不同界面
            if job == '1':
                return redirect('eatwell:restaurants')
            elif job == '2':
                return redirect('eatwell:orders')
            else:
                return HttpResponse('登录成功')
        else:
            return HttpResponse('认证失败')
    return HttpResponse('请求方式有问题')


def restaurants(request):
    restaurant_objs = Restaurant.objects.all()
    return render(request, 'restaurants.html', {"restaurant_objs": restaurant_objs})


@login_required
def orders(request):
    if request.user.userprofile.job=='2':
        order_objs = Order.objects.all()
        return render(request,'orders.html',{"order_objs":order_objs})
    else:
        return HttpResponse('没有权限查看')

def restaurant_add(request):
    if request.method == "GET":
        return render(request, 'restaurant_add.html')
    if request.method == "POST":
        name = request.POST.get("name", "")
        address = request.POST.get("address", "")

        if name and address:
            Restaurant.objects.create(name=name, address=address)
            return redirect('eatwell:index')
        else:
            return redirect('eatwell:restaurant_add')


def logoutx(request):
    logout(request)
    return redirect('eatwell:index')

# todo 抢单